<template>
  <div class="main-container container-fluid container-box px-2 px-lg-3 ">
    <div class="row">
      <!--  文章主体    -->
      <div class="col-lg-9"  style="position:relative">
        <!--  点赞收藏评分固钉    -->
        <div class="affix-container element-to-hide" style="position:absolute; left: -80px">
          <el-affix :offset="120">
            <div class="" style=" display: flex; flex-direction: column">
              <div class="card-button" @click="method.clickLikeArticle()" >
                <div class="affix-count" ><span>{{state.user.article.data.likes}}</span></div>
                <el-button style="width: 100%;height: 100%;" circle >
                  <img  v-if="!state.isLike" style="height: 20px; width: 20px;" src="/src/assets/svg/like-begin.svg" alt="svg" />
                  <img  v-else style="height: 20px; width: 20px;" src="/src/assets/svg/like-end.svg" alt="svg" />
                </el-button>
              </div>
              <div class="card-button" @click="method.clickCollectArticle()" >
                <div class="affix-count" ><span>{{state.user.article.data.star}}</span></div>
                <el-button style="width: 100%;height: 100%;" circle  >
                  <img v-if="!state.isStar" style="height: 20px; width: 20px;" src="/src/assets/svg/collect-begin.svg" alt="svg" />
                  <img v-else style="height: 20px; width: 20px;" src="/src/assets/svg/collect-end.svg" alt="svg" />
                </el-button>
              </div>
              <div class="card-button" @click="method.clickShareArticle()" >
                <el-button style="width: 100%;height: 100%;" circle >
                  <img style="height: 25px; width: 25px;" src="/src/assets/svg/share.svg" alt="svg" />
                </el-button>
              </div>
              <!--      文章评分部分 暂时关闭        -->
              <!--              <div class="card-button" @click="method.clickGradeArticle" >-->
              <!--                <div class="affix-count" ><span>{{state.article.data.rate}}</span></div>-->
              <!--                <el-button style="width: 100%;height: 100%;" circle >-->
              <!--                  <img style="height: 25px; width: 25px;" src="/src/assets/svg/grade.svg" alt="svg" />-->
              <!--                </el-button>-->
              <!--              </div>-->
            </div>
          </el-affix>
        </div>
        <!--  内容主体    -->
        <el-card class="card-body mb-3" style="padding: 20px">
          <div class="p-1">
            <div class="title fs-4 mb-2">{{state.user.article.data.title}}</div>
            <div class="author mt-2 d-flex">
              <div class="m-lg-1">
                <el-avatar size="default" :src="formatUrl(state.user.sysUser.avatar)" alt="img" class="author-avatar" style="height: 24px;width: 24px"/>
              </div>
              <div class="author-name m-lg-1">{{state.user.sysUser.nickName}}</div>
              <div class="author-tag m-lg-1 badge" style="color: #F9C851">作者</div>
              <div class="m-lg-1">|</div>
              <div class="author-time m-lg-1 " style="color: #6C757D; font-size: 13px">{{state.user.article.data.createTime}} 发表了此文章</div>
            </div>
            <div style="" >
              <el-image :src="formatUrl(state.user.article.data.covers)" style="max-height: 300px;object-fit: cover;border-radius: 6px" >  </el-image>
            </div>
            <div style="font-size: 16px;color: #6C757D;" >
              {{state.user.article.data.synopsis}}
            </div>
          </div>
          <div class="p-1">
            <div class="editor-content-view content markdown mt-3 " ref="markdown"  data-slate-editor></div>
          </div>
          <!-- 结束分割线         -->
          <el-divider>
            <el-icon> END </el-icon>
          </el-divider>
        </el-card>
        <!--   组件评论 -->
        <comment v-if="state.isShowComment" :id="route.query.id" :type="'article'" ></comment>
      </div>
      <!--  文章主体end    -->
      <!--  作者信息    -->
      <div class="col-lg-3">
        <!-- position:sticky;   粘性定位     -->
        <el-affix :offset="80" style="position:sticky;" >
          <el-card class="card-body p-0" >
            <div class="card-header border-unset p-0 radius-5"  >
              <el-image :src="defBack" style="width: 100%; max-width: max-content;max-height: 90px;object-fit: cover">  </el-image>
            </div>
            <div class="author-info">
              <div class="d-flex" >
                <el-avatar size="default" :src="formatUrl(state.user.sysUser.avatar)" style="margin-right: 10px"/>
                <div>
                  <div style="font-size: 20px" > {{state.user.sysUser.nickName}} </div>
                  <div style="font-size: 10px" > {{state.user.sysUser.email}} </div>
                </div>
              </div>
              <div class="text-container mt-1">{{state.user.sysUser.state}}</div>
              <el-divider />
              <div class="card-body pt-0 py-2 px-2" style="font-size: 14px;color: rgb(97, 102, 109);" >最近更新:{{state.user.article.data.updateTime==null?"从未更新":state.user.article.data.updateTime}}</div>
              <div class="card-body pt-0 py-2 px-2" style="font-size: 14px;color: rgb(97, 102, 109);" >发布时间:{{state.user.article.data.createTime}}</div>
              <div class="card-body pt-0 py-2 px-2 pt-2" style="font-size: 14px" >
                文章标签
                <div class="pt-2" v-if="Array.isArray(state.label) && state.label.length"  >
                  <el-tag v-for="item in state.label"  style="margin-right: 3px" type="success">{{item.label}}</el-tag>
                </div>
                <div class="pt-2" v-else>
                  <el-tag>无</el-tag>
                </div>
              </div>
              <div class="card-body pt-0 py-2 px-2 pt-2" style="font-size: 14px" >
                文章分组
                <div class="pt-2" >
                  <el-tag v-if="state.group" type="success">{{state.group}}</el-tag>
                  <el-tag v-else>无</el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-affix>
      </div>
      <!--  作者信息 end   -->
    </div>
    <!-- 评分弹出窗   -->
    <el-dialog  v-model="state.gradeDialog" title="为这篇文章评个分吧"  width="400" center style="padding: 10px;" >
      <span style="text-align: center;" >评分后会更容易推荐到喜欢的内容噢</span>
      <template #footer>
        <el-rate
            v-model="state.user.article.data.rate"
            @change="method.clickRate"
            :texts="['很差', '一般', '还行', '很好', '完美']"
            allow-half
            clearable
            size="large"
            show-text
        />
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {nextTick,onMounted, reactive, ref, watch} from "vue";
import {useRoute} from "vue-router";
import Comment from "@/components/comment/comment.vue"
import {inisHelper} from "@/utils/helper";
const route = useRoute();
import Prism from "prismjs"; // 代码高亮核心
import "prismjs/plugins/line-numbers/prism-line-numbers.min.js"; // 行号插件
import "prismjs/themes/prism-tomorrow.min.css"; // 高亮主题
import "prismjs/plugins/line-numbers/prism-line-numbers.min.css";
import {ElMessage, ElNotification} from "element-plus";
import defBack from "@/assets/img/banner/rand3.jpg"
import {
  getArticleById,
  getArticleRate,
} from "@/api/artcle/article";
import {useUserStore} from "@/store/modules/user";
import {getBlogUserInfo} from "@/api/user/user";
import {formatUrl} from "@/utils/tools/format";
import {getLikeCount, getLikeState, like} from "@/api/like/like";
const userStore = useUserStore();
const markdown =ref(null);

const  state = reactive({
  user: {
    sysUser: {
      createBy: null,
      createTime:null ,
      updateBy: null,
      updateTime:null ,
      remark: null,
      userId: null,
      deptId: null,
      userName: null,
      nickName: null,
      email:null ,
      phonenumber: null,
      sex: null,
      avatar: null,
      password: null,
      status: null,
      delFlag:null ,
      loginIp: null,
      loginDate:null ,
      dept: null,
      roles: [
        {
          createBy: null,
          createTime:null ,
          updateBy: null,
          updateTime: null,
          remark:null ,
          roleId: null,
          roleName: null,
          roleKey:null ,
          roleSort: null,
          dataScope: null,
          menuCheckStrictly: null,
          deptCheckStrictly: null,
          status:null,
          delFlag: null,
          flag: null,
          menuIds: null,
          deptIds: null,
          permissions: null,
          admin: null
        }
      ],
      roleIds: null,
      postIds: null,
      roleId: null,
      admin: null
    },
    article: {
      id: null, //文章id
      uid: null, //文章作者id
      groupId:null,
      title:'',
      likes:null,
      star:null,
      data:{
        content:"",
        likes:null,
        stars:null,
        title:null,
        avatarUrl:null,
        nickname:null,
        createTime:null,
        covers:null,
        Synopsis:null,
        email:null,
        remark:null,
        labels:null,
        group:null,
        rate:null,
        views:null
      }
    },
  },
  gradeDialog:false,
  isLike:false,
  isStar:false,
  isRate:false,
  isShowComment:true,
  group:null,
  label:null
})

const method = {
  async  init(){
    state.user.article.id = route.query.id;
    //初始化数据
    if (!inisHelper.is.empty(state.user.article.id)){
      method.getArticleInfoById();
    }
    //初始化登录数据
    if (userStore.status){
      method.isLike();
      method.isStar();
    }

  },
  /**
   * 查询文章信息
   */
  getArticleInfoById(){
    const  id =  state.user.article.id
    getArticleById(id).then(res => {
      // console.log(res)
      state.user.article.data = res.data;
      state.user.article.uid = res.data.authorId;
      state.user.article.id = res.data.id;
      state.user.article.groupId = res.data.groupId;
      state.group = res.data.group.group;
      state.label = res.data.labels;
      // 先处理图片 URL
      state.user.article.data.content = initContent(state.user.article.data.content)
      // 将处理后的内容插入到 DOM 中
      markdown.value.innerHTML = state.user.article.data.content;
      // 执行代码高量样式
      method.highlight();
      this.getUserInfoById();//获取用户信息
    })
  },
  /**
   * 获取用户信息
   */
  getUserInfoById(){
    const uid = state.user.article.uid;
    getBlogUserInfo(uid).then(res => { //请求用户信息
      state.user.sysUser = res.data
    })
  },
  getLikeCount(target){
    const  id =  state.user.article.id
    //请求后端缓存获取收藏数
    getLikeCount(target,id).then(res=>{
      switch (target){
        case 1:
          state.user.article.data.likes =res.data;
          break;
        case 2:
          state.user.article.data.stars =res.data;
          break
      }

    })
  },
  /**
   * 点击点赞文章
   */
  clickLikeArticle(){
    const id = state.user.article.id;
    // if (userStore.status){
    //   //先进行展示，后同步
    //   state.isLike =! state.isLike;
    //   if (state.isLike){
    //     state.article.data.likes++
    //   }else {
    //     state.article.data.likes--
    //   }
    // }
    like(1,id).then(res=> {
      if("点赞成功"===res.msg){
        ElNotification( {title:"提示", message: res.msg,type: 'success' })
      }
      //请求后端缓存获取收藏数
      getLikeCount(1,id).then(res=>{
        state.user.article.data.likes =res.data;
      })
      method.isLike();
      //请求后端缓存获取点赞数
      // getArticleLikeNum(id).then(res=>{
      //   state.article.data.likes = res.data
      // })
    })

  },
  /**
   * 点击收藏文章
   */
  clickCollectArticle(){
    const id = state.user.article.id;
    // if (userStore.status){
    //   // //先进行展示，后同步
    //   state.isStar =! state.isStar;
    //   if (state.isStar){
    //     state.article.data.star++
    //   }else {
    //     state.article.data.star--
    //   }
    // }
    like(2,id).then(res=>{
      if("收藏成功"===res.msg){
        ElNotification( {title:"提示", message: res.msg,type: 'success' })
      }
      //请求后端缓存获取收藏数
      getLikeCount(2,id).then(res=>{
        state.user.article.data.star =res.data;
      })
      method.isStar();
    })
  },
  /**
   * 分享
   */
  async clickShareArticle(){
    try {
      await navigator.clipboard.writeText(window.location.href);
      ElMessage.success('已经复制好地址啦,快发给小伙伴吧！');
    } catch (err) {
      console.error('Failed to copy URL: ', err);
    }
  },
  /**
   * 是否点赞
   */
  isLike(){
    getLikeState(1,state.user.article.id).then(res=>{
      state.isLike = res;
    })
  },
  /**
   * 是否收藏
   */
  isStar(){
    getLikeState(2,state.user.article.id).then(res=>{
      state.isStar =  res;
    })
  },
  /**
   * 是否评分
   */
  isRate(){


  },
  // 代码高亮插件 富文本代码块样式
  highlight: async ()=>{
    //行号插件的样式
    const preTags = markdown.value.querySelectorAll('pre');
    preTags.forEach(preTag => {
      // 如果 pre 标签内部没有 code 标签，动态添加
      if (!preTag.querySelector('code')) {
        const codeTag = document.createElement('code');
        codeTag.className = 'language-js'; // 或者其他语言
        codeTag.textContent = preTag.textContent;
        preTag.innerHTML = ''; // 清空 pre 标签内容
        preTag.appendChild(codeTag);
      }
      preTag.classList.add('line-numbers');
    });
    Prism.highlightAll();
  },
  // 点击文章评分
  clickGradeArticle(){
    state.gradeDialog =!state.gradeDialog;
  },
  clickRate(){
    const rate =state.ov.rate*2;
    const articleId= Number(state.user.article.id);
    getArticleRate({rate,articleId}).then((res)=>{
      method.clickGradeArticle();
      ElMessage.success(res.msg);
    })
  }
}
const initContent = (content) => {
  if (!content) return '';
  const baseUrl = 'http://localhost:8090';
  const regex = /<img[^>]+src="([^">]+)"/g;
  return content.replace(regex, (match, p1) => {
    const src = p1.startsWith('/') ? baseUrl + p1 : p1;
    return match.replace(p1, src);
  });
};

watch(() => state.user.article.data.content, async (newContent, oldContent) => {
  if (newContent !== oldContent) {
    // 确保 DOM 已经更新
    await nextTick();
    // 处理图片 URL
    state.user.article.data.content = initContent(newContent);
    // 更新 DOM 内容
    markdown.value.innerHTML = state.user.article.data.content;
    // 执行代码高量样式
    await method.highlight();
  }
});

watch(()=> userStore.status,() => {
  method.init();
})

onMounted( async() => {
  //页面初始化
  await method.init();
  // console.log('初始化完成')
})
</script>
<style scoped >
.editor-content-view {
  border-radius: 5px;
  padding: 0 10px;
  margin-top: 20px;
  /*overflow-x: auto;*/
  /*display: flex;*/
}
.editor-content-view p,
.editor-content-view li {
  white-space: pre-wrap; /* 保留空格 */
}
.editor-content-view blockquote {
  border-left: 8px solid #d0e5f2;
  padding: 10px 10px;
  margin: 10px 0;
  background-color: #f1f1f1;
}
.editor-content-view pre {
  flex-direction: column;
  font-family: monospace;
  padding: 3px;
  border-radius: 3px;

}
.editor-content-view pre{
  min-width: 20vw; /* 使用视口单位设置最小宽度 */
  overflow-x: auto; /* 允许水平滚动 */
  width: 100%; /* 仍然设置为 100% 以确保它不会超过父容器 */
}
@media (max-width: 1200px) {
  .editor-content-view pre {
    max-width: 85vw; /* 使用视口单位设置最大宽度 */
  }
}
.editor-content-view p img{
  width: 100%;
  max-width:800px ;
}
.editor-content-view table {
  border-collapse: collapse;
}
.editor-content-view td,
.editor-content-view th {
  border: 1px solid #ccc;
  min-width: 50px;
  height: 20px;
}
.editor-content-view th {
  background-color: #f1f1f1;
}
.editor-content-view ul,
.editor-content-view ol {
  padding-left: 20px;
}
.editor-content-view input[type="checkbox"] {
  margin-right: 5px;
}
</style>

<style scoped>

>>>.el-card__body { padding:0; }
.main-container {
  width: 1200px;
  max-width: 1200px;
}
>>>.el-rate__icon{
  font-size: 35px;
}

.affix-count{
  position:absolute;
  right: -3px;
  top: -10px;
  background-color: #40a9ff;
  padding-left: 5px;
  padding-right:5px;
  border-radius: 35%;
  font-size: 12px;
  color: #f1f1f1;
}
.card-button{
  width: 64px;
  height: 64px;
  text-align: center;
  margin-bottom: 15px;
  position:relative
}

.title {
  font-weight: bolder;
}

.author {
  color: #6C757D;
}
.author-info{
  position: relative;
  top: -5px;
  left: 15px;
}
.text-container{
  font-size: 14px;
  color: #6C757D;
  max-width: 240px;
  white-space: nowrap; /* 确保文本在一行内显示 */
  overflow: hidden; /* 隐藏超出容器的内容 */
  text-overflow: ellipsis; /* 可选，使用省略号表示文本被截断 */
}

.custom-input  {
  border: none; /* 隐藏边框 */
  /* 如果你想要完全移除边框的视觉效果，还可以添加以下样式 */
  box-shadow: none; /* 移除边框阴影（如果有的话） */
  /* 你可能还需要添加一些内边距或外边距来调整布局 */
  padding: 10px; /* 示例内边距 */
}

.custom-input:focus{
  border: none; /* 隐藏获得焦点时的边框 */
  box-shadow: none; /* 移除获得焦点时可能添加的阴影 */
  outline: none; /* 移除浏览器默认的获得焦点时的轮廓线 */
}

@media (max-width: 1200px) {
  .element-to-hide {
    display: none;
  }
}

/* 移动端隐藏固钉内容 */
@media (max-width: 1200px) {
  .affix-container {
    display: none;
  }
}
</style>
